package com.dragon.backstage.interfaces;

import com.dragon.interfaces.constant.UserConstant;
import com.dragon.interfaces.entity.User;
import com.dragon.interfaces.mapper.MenuMapper;
import com.dragon.interfaces.mapper.RoleMapper;
import com.dragon.interfaces.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 自定义权限加载接口类
 *
 * @author dragon
 * @version 1.0
 * @date 2024/8/5 14:23
 */
@Component
public class StpInterface implements cn.dev33.satoken.stp.StpInterface {

    @Resource
    private UserMapper userMapper;
    @Resource
    private MenuMapper menuMapper;
    @Resource
    private RoleMapper roleMapper;


    /**
     * 返回指定账号id所拥有的权限码集合
     *
     * @param loginId   账号id
     * @param loginType 账号类型
     * @return 该账号id具有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 权限可以缓存起来避免实时查询
        List<String> permissions = new ArrayList<>();

        User user = userMapper.selectById(Long.parseLong((String) loginId));
        if (Objects.nonNull(user)) {
            if (UserConstant.SUPER_ADMIN_ACCOUNT.equals(user.getAccount())) {
                // 超级管理员获取所有权限
                permissions = menuMapper.selectAllPermission();
            } else {
                permissions = userMapper.selectUserPermissionByUserId(user.getUserId());
            }
        }

        return permissions;
    }

    /**
     * 返回指定账号id所拥有的角色标识集合
     *
     * @param loginId   账号id
     * @param loginType 账号类型
     * @return 该账号id具有的角色标识集合
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> roleKeys = new ArrayList<>();

        User user = userMapper.selectById(Long.parseLong((String) loginId));
        if (Objects.nonNull(user)) {
            if (UserConstant.SUPER_ADMIN_ACCOUNT.equals(user.getAccount())) {
                // 超级管理员获取所有权限
                roleKeys = roleMapper.selectAllRoleKey();
            } else {
                roleKeys = roleMapper.selectUserRoleKeyByUserId(user.getUserId());
            }
        }

        return roleKeys;
    }

}
